package pl.veneo.wigprofit.ctrl {
	import pl.veneo.wigprofit.model.Configuration;
	import pl.veneo.wigprofit.ctrl.events.ChartResizeEvent;
	import pl.veneo.wigprofit.ctrl.events.ModelUpdateEvent;
	import pl.veneo.wigprofit.model.ChartDataModel;
	import pl.veneo.wigprofit.view.ChartView;

	import flash.events.EventDispatcher;

	/**
	 * @author Tomasz Swierszcz, fiodorkrk@gmail.com
	 */
	public class ChartControler extends EventDispatcher {
		private var _model : ChartDataModel;
		private var _view : ChartView;

		public function ChartControler(model : ChartDataModel, view : ChartView) {
			super();
			_view = view;
			_view.addEventListener(ChartResizeEvent.ON_CHART_RESIZE, onChartZoomUpdate);
			_view.addEventListener(ChartResizeEvent.ON_CHART_SLIDE, oneChartSlideUpdate);
			_view.addEventListener(ChartResizeEvent.ON_RESET_ZOOM, onResetZoom);
			_model = model;
			_model.addEventListener(ModelUpdateEvent.ON_DATA_UPDATED, onModelUpdated);
			_model.updateData();
		}

		private function onResetZoom(event : ChartResizeEvent) : void {
		
			_view.buildZoomForPeriod(_model.getDataForPeriod(_model.dataStart, _model.dataEnd));
			
		}
		
		private function oneChartSlideUpdate(event : ChartResizeEvent) : void {
			
			var start:Date = event.start;
			start.hours = 0;
			start.minutes = 0;
			start.seconds = 0;
			start.milliseconds = 0;
			var end:Date = event.end;
			end.hours = 0;
			end.minutes = 0;
			end.seconds = 0;
			end.milliseconds = 0;
			_view.buildSlideForPeriod(_model.getDataForPeriod(start, end));
			
		}

		private function onChartZoomUpdate(event : ChartResizeEvent) : void {
			
			var start:Date = event.start;
			start.hours = 0;
			start.minutes = 0;
			start.seconds = 0;
			start.milliseconds = 0;
			var end:Date = event.end;
			end.hours = 0;
			end.minutes = 0;
			end.seconds = 0;
			end.milliseconds = 0;
			_view.buildZoomForPeriod(_model.getDataForPeriod(start, end));
			
		}

		public function onModelUpdated(event : ModelUpdateEvent) : void {
			_model.removeEventListener(ModelUpdateEvent.ON_DATA_UPDATED, onModelUpdated);
			_view.buildChartForPeriod(_model.getDataForPeriod(event.start, event.end));
			
			var start : Date = event.start;
			var end : Date = event.end;
			
			if(Configuration.getInstance().beginDateSet && Configuration.getInstance().beginDate>=event.start)
			start = Configuration.getInstance().beginDate;
			
			if(Configuration.getInstance().endDateSet && Configuration.getInstance().endDate<= event.end)
			end = Configuration.getInstance().endDate;
			
			if(Configuration.getInstance().beginDateSet || Configuration.getInstance().endDateSet){
				_view.buildZoomForPeriod(_model.getDataForPeriod(start, end));
				_view.showButton();
			}
			
			
		}
	}
}
